package pub.wkq.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 构建简单模式的消费者，监听消费消息
 */
public class FooConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 创建连接工厂以及相关的参数配置
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("43.136.173.173");
        factory.setPort(5672);
        factory.setVirtualHost("hire");
        factory.setUsername("hire");
        factory.setPassword("hire");
        //2. 通过工厂创建连接
        Connection connection = factory.newConnection();
        //3. 通过连接创建通道
        Channel channel = connection.createChannel();

        channel.queueDeclare("hello", true, false, false, null);
        Consumer consumer = new DefaultConsumer(channel) {
            /**
             * @param consumerTag 消费者标签，用来标识消费者，在监听队列时设置channel.basicConsume
             * @param envelope 信封,比如交换机路由等信息
             * @param properties 消息属性
             * @param body 消息内容
             * @throws IOException 异常
             */
            @Override
            public void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag: " + consumerTag);
                System.out.println("envelope: " + envelope);
                System.out.println("properties: " + properties);
                System.out.println("body: " + new String(body));
            }
        };
        /**
         * queue: 队列名称
         * autoAck: 是否自动确认，true：自动确认(告知消费者已经消费的确认通知)，false：手动确认
         * callback: 回调函数，消费者接收到消息后，会调用这个函数
         *
         */
        channel.basicConsume("hello", true, consumer);
    }
}
